package com.ttctracker.map;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.ttctracker.classes.Prediction;
import com.ttctracker.classes.StopItem;



public class StopPredictionsHandler extends DefaultHandler{
	
	private HashMap<String, StopItem> stopItems;
	private StopItem tempStopItem;
	private Prediction tempStopPrediction;
	private String directionTitle;
	private boolean isSkipping=false;
	
	public HashMap<String, StopItem> getStopItems() {
		if (stopItems!=null) {
			if (!stopItems.isEmpty()) {
				return stopItems;
			}
		}
		return null;
	}
	
	@Override
	public void startDocument() throws SAXException {
		stopItems=new HashMap<String, StopItem>();
		//tempStopItem=new StopItem();
		
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (localName.equals("predictions")) {
			if (!isSkipping) {
				tempStopItem.set_prediction(tempStopPrediction);
				stopItems.put(directionTitle, tempStopItem);
			}else {
				isSkipping=false;
			}
			
			//tempStopPrediction.clear();
			return;
		}
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (localName.equals("predictions")&&!isSkipping) {
			tempStopItem = new StopItem();
			tempStopPrediction=new Prediction(0);
			String routeTag=attributes.getValue("routeTag");
			if (routeTag.length()>2&&routeTag.startsWith("3")) {
				isSkipping=true;
				return;
			}
			
			tempStopItem.set_tag(attributes.getValue("stopTag"));
			tempStopItem.set_title(attributes.getValue("stopTitle"));
			tempStopItem.set_routeTag(routeTag);
			String noPredictionTextString = attributes
					.getValue("dirTitleBecauseNoPredictions");
			if (noPredictionTextString != null) {
				tempStopPrediction.add(-1);
				directionTitle=noPredictionTextString;
				// setTempRouteItem();
			}
			return;
		}
		if (localName.equals("direction")&&!isSkipping) {
			directionTitle=attributes.getValue("title");
			return;
		}
		if (localName.equals("prediction")&&!isSkipping) {

			String tempValue = attributes.getValue("minutes");
			String prediction = tempValue != null ? tempValue : "-1";
			tempStopPrediction.add(Integer.parseInt(prediction));
			// setTempRouteItem();

			return;
		}
	}
	
}
